/*{
单元名称：物流页面behavior
单元功能：获取销售单、货物列表、获取运输点、定位
所属模块功能：
创建人：yan
创建时间：230902
修改人：
修改时间：
}*/
import {GetUrlString} from "../utils/utils";

module.exports = Behavior({
  data: {

    //销售单信息
    salesOrder: [
      /*{
        'xiaoshouchuku': 'XOUT131533',
        'songhuodizhi': '浙江省杭州余杭仁和街道',
      },
      {
        'xiaoshouchuku': 'XOUT131534',
        'songhuodizhi': '浙江省杭州余杭仁和街道',
      },*/
    ],
    //货物信息
    goodsList: [
      /*{
        'chanpinmingcheng': '成品-柠檬',
        'shifashuliang': '20.0000',
        'danwei': '箱',
      }*/
    ],

    //运输点弹窗显示标识
    showPoint: false,

    // 验证标识
    validFlag: false,
    // 验证表单项
    validObj: {},
    //录入数据
    inputData: {}
  },
  methods: {
    //微信扫一扫
    wxscanCode(){
      return new Promise(resolve => {
        // resolve('ddh230904001');
        /*let pages = getCurrentPages(),
          perpage = pages[pages.length - 1], //当前页面
          orderid = '202308211103115073035251',
          url = `/${perpage.route}?orderid=${orderid}`
        wx.redirectTo({url});*/
        wx.scanCode({
          success: async (res) => {
            if (res.errMsg === "scanCode:ok") {
              console.log("扫码结果");
              console.log(res);
              let {result} = res,
                orderid = result;
              if (result.indexOf('http://yfgpwebapi.fszyrj.com/wlxcx/') >= 0){
                let obj = {};
                /* for (let i = 1;i<8;i++){
                  let item = 'param' + i
                  obj[item] = GetUrlString(result,item);
                }
                console.log(obj);
                orderid = obj.param4 || ''*/
                let dm =  wx.$util.GetUrlString(result,'dm');
                if (dm){
                  await this.getShortSource(dm).then(res => {
                    if (res) {
                      let arr = res.split('&');
                      arr.forEach(item => {
                        let kv = item.split('=');
                        obj[kv[0]] = kv[1]
                      });
                    }
                  })
                } else {
                  for (let i = 1;i<8;i++){
                    let item = 'param' + i
                    obj[item] =  wx.$util.GetUrlString(result,item);
                  }
                }
                orderid = obj.param4 || ''
              }

              resolve(orderid);

              // let pages = getCurrentPages(),
              //   perpage = pages[pages.length - 1]; //当前页面
                // orderid = '202308211103115073035251';
                // url = `/${perpage.route}?orderid=${orderid}`
              // wx.redirectTo({url});
              this.setData({orderid})
              this.ready();
            }
          },
          fail: (res) => {
            console.log(res);
            wx.$toast('扫码失败')
          }
        })
      })
    },

    //显示运输点
    onShowPoint(){
      // this.wxLocation();
      this.setData({showPoint: true})
    },
    //确定选择
    onConfirmPoint(e){
      let {info} = e.detail,
        url = `WLAuth/GenZongJiLu`,
        {orderid } = this.data,
        post = {
          "yundanhao": orderid,
          "shujushijian": wx.$util.formatDate(new Date(),'yyyy-MM-dd HH:mm:ss'),
          ...info
        };
      wx.$post(5,url,post).then(res => {
        if (res.errcode != 0) return;
        this.setData({showPoint: false});
        wx.$toast('上传成功');
      })
    },

    // 记录验证表单项
    validIpt(e) {
      let { validObj, } = this.data
      this.data.validObj = {
        ...validObj,
        ...e.detail,
      };
    },
    //验证数据
    validForm(validObj){
      return new Promise((resolve, reject) => {
        let valid = Object.values(validObj).includes(false) ? false : true;
        resolve(valid)
      })
    },
    //  字段变化
    bindChange(e){
      let detail = e.detail,
        field = detail.field,
        id = field.field_id || field.fieldName,
        type = field.type,
        val = detail.val;

      if (type === 'num' || type === 'currency' || type === 'percent'){
        val = val ? val : null
      }

      //赋值
      this.data.inputData[id] = val;

    },

  //  运单号输入搜索
    bindSearch(e){
      let {value} = e.detail;
      if (!value) return;
      this.setData({orderid: value})
      this.ready();
    },

  //  获取货物列表
    getGoodsByOrder(id){
      return new Promise(resolve => {
        let url = `WLAuth/HuoWuHuiZong/${id}`;
        wx.$get(5,url).then(res => {
          resolve();
          if (res.errcode !== 0) return;
          let goodsList = res.data.row || [],
            sum = 0;
          goodsList.forEach(item => {
            sum += Number(item.shuliang)
          })
          this.setData({goodsList,sum});
        })
      })
    },

  //  获取销售单
    getSalesByOrder(id){
      return new Promise(resolve => {
        let url = `WLAuth/XiaoShouChuKuDan/${id}`;
        wx.$get(5,url).then(res => {
          if (res.errcode !== 0 )return;
          let salesOrder = res.data.row || [];
          this.setData({salesOrder});
          resolve(salesOrder)
        })
      })
    },

  //  跳转到销售单详情
    navToSalesDetail(e){
      let {url, item} = e.currentTarget.dataset;
      wx.setStorageSync('salesOrder',item);
      wx.navigateTo({
        url
      })
    },

  //  获取运单列表


  //  获取运输点
    getTransitPoint(){
      return new Promise(resolve => {
        let url = '';
        this.wxLocation().then(res => {
          let{latitude, longitude} = res,
            post = {latitude, longitude}
          wx.$post(1,url,post).then(res => {
            if (res.errcode != 0) return
            let rows = res.data.row,
              option = [];
            rows.forEach(item => {
              let {name, id} = item;
              option.push({name, id})
            })
          })
        })
      })
    },


  //  获取当前位置
    wxLocation(){
      return new Promise(resolve => {
        // resolve({latitude:23.035508897569443 , longitude:113.11290771484374});
        wx.getLocation({
          type: 'gcj02', // 比较精确
          success: (res) => {
            console.log(res);
            resolve(res);
          }
        })
      })
    },

  //  短码换取二维码参数
    getShortSource(code){
      return new Promise(resolve => {
        let url = 'WL/Get_short_to_Source'
        wx.$get(5,url,{data_in: code}).then(res => {
          if (res.errcode != 0) {
            resolve()
            return;
          }
          let code = res.data.row[0] && res.data.row[0].yuanma
          resolve(code)
        })
      })
    },

  //  加载时调用
    ready(){
      let {orderid} = this.data;
      if (!orderid) return;
      wx.showLoading({mask: true})
      Promise.all([
        this.getGoodsByOrder(orderid),
        this.getSalesByOrder(orderid)
      ]).then(res => {
        wx.hideLoading();
      })

    },


    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

      wx.getSetting({
        success(res){
          if (!res.authSetting['scope.userLocation']){
            console.log('未打开定位服务');
            wx.openSetting();
            wx.getLocation({
              type: 'gcj02', // 比较精确
              success: (res) => {
                console.log(res);
              },
              fail: (res) =>{
                wx.showModal({
                  title: '定位服务未打开',
                  content: '请在系统设置中打开位置授权，以便我们为您提供更好的服务',
                  confirmText: '去开启',
                  success: (res) => {
                    if(res.confirm) {
                      wx.openSetting();
                    }
                  },
                });
              }
            })

          }else {
            const systemSetting = wx.getSystemSetting()
            if (!systemSetting.locationEnabled) {
              wx.showModal({
                title: '定位服务未打开',
                content: '请在系统设置中打开位置授权，以便我们为您提供更好的服务',
                confirmText: '确定',
                showCancel: false,
                success: (res) => {
                  if(res.confirm) {
                    wx.navigateTo({url:'/SlagCar/OpenLocationGuide/OpenLocationGuide'})
                  }
                },
              })
            }
          }

        }
      })
    },
  }
})
